// 智能任务分类服务
import type { Task } from '@/stores/taskStore'
import type { 
  TaskClassification, 
  TimeBasedCategory, 
  StatusBasedCategory,
  SmartClassificationConfig 
} from '@/types/smartList'

export class SmartClassificationService {
  private config: SmartClassificationConfig

  constructor(config: SmartClassificationConfig) {
    this.config = config
  }

  /**
   * 对单个任务进行智能分类
   */
  classifyTask(task: Task): TaskClassification {
    const timeCategory = this.getTimeBasedCategory(task)
    const statusCategory = this.getStatusBasedCategory(task)
    const categories = this.generateCategoryList(task, timeCategory, statusCategory)

    return {
      taskId: task.id,
      categories,
      timeCategory,
      statusCategory,
      lastUpdated: new Date()
    }
  }

  /**
   * 批量分类任务
   */
  classifyTasks(tasks: Task[]): TaskClassification[] {
    return tasks.map(task => this.classifyTask(task))
  }

  /**
   * 获取时间维度分类
   */
  private getTimeBasedCategory(task: Task): TimeBasedCategory {
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000)
    const weekEnd = new Date(today.getTime() + (7 - today.getDay()) * 24 * 60 * 60 * 1000)

    let isToday = false
    let isTomorrow = false
    let isThisWeek = false
    let isOverdue = false
    let isUpcoming = false

    // 检查截止日期
    if (task.dueDate) {
      const dueDate = new Date(task.dueDate)
      const dueDateOnly = new Date(dueDate.getFullYear(), dueDate.getMonth(), dueDate.getDate())
      
      if (dueDateOnly.getTime() === today.getTime()) {
        isToday = true
      } else if (dueDateOnly.getTime() === tomorrow.getTime()) {
        isTomorrow = true
      } else if (dueDateOnly <= weekEnd && dueDateOnly >= today) {
        isThisWeek = true
      } else if (dueDateOnly < today && !task.completed) {
        isOverdue = true
      } else if (dueDateOnly > today) {
        isUpcoming = true
      }
    }

    // 检查提醒时间
    if (task.reminder && !task.completed) {
      const reminderDate = new Date(task.reminder)
      const reminderDateOnly = new Date(reminderDate.getFullYear(), reminderDate.getMonth(), reminderDate.getDate())
      
      if (reminderDateOnly.getTime() === today.getTime()) {
        isToday = true
      } else if (reminderDateOnly.getTime() === tomorrow.getTime()) {
        isTomorrow = true
      }
    }

    // 如果是今天创建的任务且没有设置截止日期，也归类为今天
    if (!task.dueDate && !task.reminder) {
      const createdDate = new Date(task.createdAt)
      const createdDateOnly = new Date(createdDate.getFullYear(), createdDate.getMonth(), createdDate.getDate())
      if (createdDateOnly.getTime() === today.getTime()) {
        isToday = true
      }
    }

    return {
      today: isToday,
      tomorrow: isTomorrow,
      thisWeek: isThisWeek,
      overdue: isOverdue,
      upcoming: isUpcoming
    }
  }

  /**
   * 获取状态维度分类
   */
  private getStatusBasedCategory(task: Task): StatusBasedCategory {
    const hasReminder = !!task.reminder
    const hasDeadline = !!task.dueDate
    const isImportant = task.isImportant || this.isImportantByKeywords(task.title)

    return {
      completed: task.completed,
      pending: !task.completed,
      important: isImportant,
      hasReminder,
      hasDeadline
    }
  }

  /**
   * 根据关键词判断任务是否重要
   */
  private isImportantByKeywords(title: string): boolean {
    const lowerTitle = title.toLowerCase()
    return this.config.importantKeywords.some(keyword => 
      lowerTitle.includes(keyword.toLowerCase())
    )
  }

  /**
   * 生成任务所属的清单ID列表
   */
  private generateCategoryList(
    task: Task, 
    timeCategory: TimeBasedCategory, 
    statusCategory: StatusBasedCategory
  ): string[] {
    const categories: string[] = []

    // 时间维度分类
    if (timeCategory.today) categories.push('today')
    if (timeCategory.tomorrow) categories.push('tomorrow')
    if (timeCategory.thisWeek) categories.push('week')
    if (timeCategory.overdue) categories.push('overdue')
    if (timeCategory.upcoming) categories.push('upcoming')

    // 状态维度分类
    if (statusCategory.completed) categories.push('completed')
    if (statusCategory.important) categories.push('important')
    if (statusCategory.hasDeadline) categories.push('planned')

    // 如果任务有自定义清单ID，也要包含
    if (task.listIds) {
      categories.push(...task.listIds)
    }

    // 默认分类：如果没有其他分类，归入任务清单
    if (categories.length === 0 || (!statusCategory.completed && categories.every(cat => cat === 'completed'))) {
      categories.push('tasks')
    }

    return [...new Set(categories)] // 去重
  }

  /**
   * 更新分类配置
   */
  updateConfig(config: Partial<SmartClassificationConfig>) {
    this.config = { ...this.config, ...config }
  }

  /**
   * 获取当前配置
   */
  getConfig(): SmartClassificationConfig {
    return { ...this.config }
  }
}

// 默认配置
export const defaultSmartClassificationConfig: SmartClassificationConfig = {
  enableAutoClassification: true,
  timeZone: 'Asia/Shanghai',
  workingHours: {
    start: '09:00',
    end: '18:00'
  },
  weekendDays: [0, 6], // 周日和周六
  importantKeywords: ['紧急', '重要', '优先', '立即', '马上', '尽快', '关键', '核心']
}